package com.example.photography.Activity;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.photography.MainActivity;
import com.example.photography.MainActivity2;
import com.example.photography.Model;
import com.example.photography.R;
import com.example.photography.bean.UserBean;
import com.example.photography.common.AppNetConfig;
import com.example.photography.common.BaseActivity;
import com.example.photography.common.Constant;
import com.example.photography.util.Util;
import com.example.photography.view.LoadingDialog;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Login_activity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.et_phote)
    EditText etPhote;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.tv_forget)
    TextView tvForget;
    @BindView(R.id.bt_login)
    Button btLogin;
    @BindView(R.id.bt_register)
    Button btRegister;
    private String user_password;
    private String user_phone;
    private String id_unique;
    private String id;
    private String message;
    private String head_url;
    private String name;
    private String hr_sign;


    @Override
    protected void initData() {

        tvForget.setOnClickListener(this);
        btLogin.setOnClickListener(this);
        btRegister.setOnClickListener(this);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.login;
    }


    @Override
    public void onClick(View view) {
        if (tvForget.equals(view)) {

        } else if (btLogin.equals(view)) {
            login();

        } else if (btRegister.equals(view)) {
            goToActivity(Register_activity.class, new Bundle());
        }

    }

    //todo 后台接口没开就会报错 加载dialog有问题待解决
    private void login() {
        user_password = etPassword.getText().toString().trim();
        user_phone = etPhote.getText().toString().trim();
        if (user_password.equals("") || user_phone.equals("")) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Util.showToast(getApplicationContext(), "手机号密码不能为空");
                }
            });
            return;
        }
        //开启等待动画
        LoadingDialog.getInstance(Login_activity.this).show();
        OkHttpClient client = new OkHttpClient();
        //POST请求
        FormBody formBody = new FormBody.Builder()
                .add("password", user_password)
                .add("phone", user_phone)
                .build();
        Request request = new Request.Builder()
                .url(AppNetConfig.login)
                .post(formBody)                //默认就是GET请求就可以不写，这里是post
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        message = "后台君好像生病了~";
                        mHandler.sendEmptyMessageDelayed(1, 0);//关闭等待动画，0延时
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonString = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(jsonString);

                    int result = Integer.parseInt(jsonObject.getString("status"));
                    message = jsonObject.getString("msg");
                    if (result == 202) {//登录成功
                        JSONObject Object = jsonObject.getJSONObject("data");
                        JSONObject user = Object.getJSONObject("user");
                        JSONObject userIfo = Object.getJSONObject("user_info");
                        id = user.getString("id");
                        id_unique = user.getString("id_unique");

                        head_url = userIfo.getString("head_url");
                        name = userIfo.getString("name");
                        hr_sign = userIfo.getString("hr_sign");
                        mHandler.sendEmptyMessageDelayed(2, 0);//关闭等待动画，0延时
                    } else if (result == 405) {//账号密码错误
                        mHandler.sendEmptyMessageDelayed(1, 0);//关闭等待动画，0延时
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    message = e.toString();
                    mHandler.sendEmptyMessageDelayed(1, 0);//关闭等待动画，0延时

                }
            }
        });

    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1://登录失败
                    LoadingDialog.getInstance(Login_activity.this).dismiss();
                    Util.showToast(Login_activity.this, message);
                    break;
                case 2://登录成功
                    Util.showToast(getApplicationContext(), "登录成功,请稍后...");
                    LoadingDialog.getInstance(Login_activity.this).dismiss();
                    action();
                    //todo 两次登录。耗时太大
                    //去环信服务器登录
                    EMClient.getInstance().login(id_unique, user_password, new EMCallBack() {//账号，密码，接口回调
                        @Override
                        public void onSuccess() {
                            EMClient.getInstance().groupManager().loadAllGroups();
                            EMClient.getInstance().chatManager().loadAllConversations();
                        }

                        @Override
                        public void onError(int code, String error) {

                        }

                        @Override
                        public void onProgress(int progress, String status) {

                        }
                    });

                    break;

            }
        }
    };

    private void action() {
        saveMessage();
        //获取全局UID
        Constant.UID = id_unique;
        //更新数据表
        UserBean.User user = new UserBean.User(id, id_unique, user_phone, user_password);
        UserBean.UserInfo userInfo = new UserBean.UserInfo(id_unique, head_url, name, hr_sign);
        Model.getInstance().getUerAccountDao().addAccount(user);
        //对模型层数据的处理
        //1. 初始化对象DBManger,DBHelper，建表
        Model.getInstance().loginSuccess(user);
        //2. 存数据
        Model.getInstance().getDbManger().getUserInfoDao().saveUserInfo(userInfo);
        goToActivity(MainActivity2.class, new Bundle());
        removeCurrentActivity();
    }

    /**
     * 保存用户登录过
     */
    private void saveMessage() {
        SharedPreferences preferences = getSharedPreferences("isLogin", MODE_PRIVATE);
        //实例化Editor对象
        SharedPreferences.Editor editor = preferences.edit();
        //存入数据
        //储存id
        editor.putString("UID", id_unique);
        //提交修改
        editor.apply();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //移除所有的未被执行的消息
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}



